<template>
  <view class="verify-new">
    <!-- 扫码核销模式 -->
    <view v-if="verifyType === 'scan'" class="scan-mode">
      <view class="scan-header">
        <text class="scan-title">扫码核销</text>
        <text class="scan-desc">请将团购券二维码放入扫描框内</text>
      </view>
      
      <view class="scan-container">
        <view class="scan-frame">
          <view class="scan-line"></view>
          <view class="scan-corners">
            <view class="corner top-left"></view>
            <view class="corner top-right"></view>
            <view class="corner bottom-left"></view>
            <view class="corner bottom-right"></view>
          </view>
        </view>
        
        <view class="scan-tips">
          <text class="tips-text">将二维码放入框内，即可自动扫描</text>
        </view>
      </view>
      
      <view class="scan-actions">
        <button class="action-btn secondary" @click="switchToManual">
          手动输入
        </button>
        <button class="action-btn primary" @click="startScan">
          开始扫描
        </button>
      </view>
    </view>

    <!-- 手动核销模式 -->
    <view v-else class="manual-mode">
      <view class="manual-header">
        <text class="manual-title">手动核销</text>
        <text class="manual-desc">请输入团购券核销码</text>
      </view>
      
      <view class="manual-form">
        <uni-forms ref="formRef" :model="formData" :rules="formRules">
          <uni-forms-item name="verifyCode" label="核销码" required>
            <uni-easyinput 
              v-model="formData.verifyCode" 
              placeholder="请输入核销码"
              :clearable="true"
              :focus="true"
            />
          </uni-forms-item>
          
          <uni-forms-item name="remark" label="备注">
            <uni-easyinput 
              v-model="formData.remark" 
              type="textarea"
              placeholder="请输入备注信息（可选）"
              :autoHeight="true"
              maxlength="200"
            />
          </uni-forms-item>
        </uni-forms>
      </view>
      
      <view class="manual-actions">
        <button class="action-btn secondary" @click="switchToScan">
          扫码核销
        </button>
        <button class="action-btn primary" @click="submitVerify" :loading="submitting">
          确认核销
        </button>
      </view>
    </view>

    <!-- 核销结果弹窗 -->
    <uni-popup ref="resultPopup" type="center" :mask-click="false">
      <view class="result-popup">
        <view class="result-icon" :class="{ success: verifyResult.success, error: !verifyResult.success }">
          <uni-icons 
            :type="verifyResult.success ? 'checkmarkempty' : 'closeempty'" 
            size="48" 
            :color="verifyResult.success ? '#52C41A' : '#FF4D4F'" 
          />
        </view>
        
        <text class="result-title">
          {{ verifyResult.success ? '核销成功' : '核销失败' }}
        </text>
        
        <text class="result-message">{{ verifyResult.message }}</text>
        
        <view class="result-details" v-if="verifyResult.success && verifyResult.data">
          <view class="detail-item">
            <text class="detail-label">订单号：</text>
            <text class="detail-value">{{ verifyResult.data.orderNo }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">用户名：</text>
            <text class="detail-value">{{ verifyResult.data.username }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">核销金额：</text>
            <text class="detail-value">¥{{ formatPrice(verifyResult.data.amount) }}</text>
          </view>
        </view>
        
        <view class="result-actions">
          <button class="result-btn secondary" @click="closeResult">
            关闭
          </button>
          <button class="result-btn primary" @click="continueVerify" v-if="verifyResult.success">
            继续核销
          </button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { verifyApi } from '@/api/groupbuy';

// 响应式数据
const verifyType = ref<'scan' | 'manual'>('scan');
const submitting = ref(false);

// 表单数据
const formData = ref({
  verifyCode: '',
  remark: '',
});

// 表单验证规则
const formRules = ref({
  verifyCode: {
    rules: [{ required: true, errorMessage: '请输入核销码' }]
  }
});

// 核销结果
const verifyResult = ref({
  success: false,
  message: '',
  data: null as any,
});

// 引用
const formRef = ref();
const resultPopup = ref();

// 格式化价格
const formatPrice = (price: number) => {
  return (price / 100).toFixed(2);
};

// 切换到手动模式
const switchToManual = () => {
  verifyType.value = 'manual';
};

// 切换到扫码模式
const switchToScan = () => {
  verifyType.value = 'scan';
};

// 开始扫描
const startScan = () => {
  // 调用uni-app的扫码API
  uni.scanCode({
    success: (res) => {
      console.log('扫码结果:', res);
      handleScanResult(res.result);
    },
    fail: (err) => {
      console.error('扫码失败:', err);
      uni.showToast({
        title: '扫码失败',
        icon: 'none',
      });
    }
  });
};

// 处理扫码结果
const handleScanResult = async (code: string) => {
  try {
    submitting.value = true;
    const res = await verifyApi.scanVerify(code);
    
    verifyResult.value = {
      success: res.success,
      message: res.message || (res.success ? '核销成功' : '核销失败'),
      data: res.data,
    };
    
    resultPopup.value.open();
  } catch (error) {
    console.error('扫码核销失败:', error);
    verifyResult.value = {
      success: false,
      message: '网络错误，请重试',
      data: null,
    };
    resultPopup.value.open();
  } finally {
    submitting.value = false;
  }
};

// 提交手动核销
const submitVerify = async () => {
  try {
    const valid = await formRef.value.validate();
    if (!valid) return;
    
    submitting.value = true;
    const res = await verifyApi.manualVerify(formData.value.verifyCode, formData.value.remark);
    
    verifyResult.value = {
      success: res.success,
      message: res.message || (res.success ? '核销成功' : '核销失败'),
      data: res.data,
    };
    
    resultPopup.value.open();
    
    if (res.success) {
      // 清空表单
      formData.value.verifyCode = '';
      formData.value.remark = '';
    }
  } catch (error) {
    console.error('手动核销失败:', error);
    verifyResult.value = {
      success: false,
      message: '网络错误，请重试',
      data: null,
    };
    resultPopup.value.open();
  } finally {
    submitting.value = false;
  }
};

// 关闭结果弹窗
const closeResult = () => {
  resultPopup.value.close();
  if (verifyResult.value.success) {
    // 核销成功后返回上一页
    setTimeout(() => {
      uni.navigateBack();
    }, 300);
  }
};

// 继续核销
const continueVerify = () => {
  resultPopup.value.close();
  // 重置表单或继续扫码
  if (verifyType.value === 'manual') {
    formData.value.verifyCode = '';
    formData.value.remark = '';
  }
};

// 页面加载
onMounted(() => {
  // 获取页面参数
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = (currentPage as any).options;
  
  if (options.type) {
    verifyType.value = options.type as 'scan' | 'manual';
  }
});
</script>

<style lang="scss" scoped>
.verify-new {
  height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.scan-mode,
.manual-mode {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 32rpx;
}

.scan-header,
.manual-header {
  text-align: center;
  margin-bottom: 64rpx;
  
  .scan-title,
  .manual-title {
    font-size: 36rpx;
    font-weight: 600;
    color: #333;
    display: block;
    margin-bottom: 16rpx;
  }
  
  .scan-desc,
  .manual-desc {
    font-size: 28rpx;
    color: #666;
  }
}

.scan-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  
  .scan-frame {
    position: relative;
    width: 500rpx;
    height: 500rpx;
    margin-bottom: 64rpx;
    
    .scan-line {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      height: 4rpx;
      background: linear-gradient(90deg, transparent 0%, #1890FF 50%, transparent 100%);
      animation: scanLine 2s linear infinite;
    }
    
    .scan-corners {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      
      .corner {
        position: absolute;
        width: 60rpx;
        height: 60rpx;
        border: 6rpx solid #1890FF;
        
        &.top-left {
          top: 0;
          left: 0;
          border-right: none;
          border-bottom: none;
        }
        
        &.top-right {
          top: 0;
          right: 0;
          border-left: none;
          border-bottom: none;
        }
        
        &.bottom-left {
          bottom: 0;
          left: 0;
          border-right: none;
          border-top: none;
        }
        
        &.bottom-right {
          bottom: 0;
          right: 0;
          border-left: none;
          border-top: none;
        }
      }
    }
  }
  
  .scan-tips {
    .tips-text {
      font-size: 26rpx;
      color: #999;
    }
  }
}

@keyframes scanLine {
  0% {
    top: 0;
  }
  100% {
    top: 100%;
  }
}

.manual-form {
  flex: 1;
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 32rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.scan-actions,
.manual-actions {
  display: flex;
  gap: 24rpx;
  
  .action-btn {
    flex: 1;
    height: 88rpx;
    border-radius: 12rpx;
    font-size: 32rpx;
    border: none;
    
    &.primary {
      background: #1890FF;
      color: #fff;
    }
    
    &.secondary {
      background: #f5f5f5;
      color: #666;
    }
  }
}

.result-popup {
  background: #fff;
  border-radius: 16rpx;
  padding: 48rpx 32rpx 32rpx;
  width: 600rpx;
  text-align: center;
  
  .result-icon {
    width: 120rpx;
    height: 120rpx;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 32rpx;
    
    &.success {
      background: rgba(82, 196, 26, 0.1);
    }
    
    &.error {
      background: rgba(255, 77, 79, 0.1);
    }
  }
  
  .result-title {
    font-size: 36rpx;
    font-weight: 600;
    color: #333;
    display: block;
    margin-bottom: 16rpx;
  }
  
  .result-message {
    font-size: 28rpx;
    color: #666;
    display: block;
    margin-bottom: 32rpx;
  }
  
  .result-details {
    background: #f9f9f9;
    border-radius: 12rpx;
    padding: 24rpx;
    margin-bottom: 32rpx;
    text-align: left;
    
    .detail-item {
      display: flex;
      margin-bottom: 16rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .detail-label {
        width: 160rpx;
        font-size: 26rpx;
        color: #666;
        flex-shrink: 0;
      }
      
      .detail-value {
        flex: 1;
        font-size: 26rpx;
        color: #333;
      }
    }
  }
  
  .result-actions {
    display: flex;
    gap: 24rpx;
    
    .result-btn {
      flex: 1;
      height: 72rpx;
      border-radius: 8rpx;
      font-size: 28rpx;
      border: none;
      
      &.primary {
        background: #1890FF;
        color: #fff;
      }
      
      &.secondary {
        background: #f5f5f5;
        color: #666;
      }
    }
  }
}
</style>